package com.junshang.JUC_day1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

/**
 * Created by shangjun on 2017/3/18.
 */
public class TestLock {
    public static void main(String[] args) {
        Ticket t = new Ticket();

        new Thread(t, "一号窗口").start();
        new Thread(t, "二号窗口").start();
        new Thread(t, "三号窗口").start();
    }
}

class Ticket implements Runnable {
    private int tickt = 100;//设置初始有多少张票
    private Lock lock = new ReentrantLock();

    public void run() {
        while (tickt > 0) {
            lock.lock();//加锁
            try {
                if (tickt > 0) {
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                    }
                    System.out.println(Thread.currentThread().getName() + "完成售票，余票为:" + --tickt);//Thread.currentThread的作用相当于this，表示当前线程
                }
            } finally {
                lock.unlock();//释放锁
            }
//            if (tickt==0) break;
            System.out.println(Thread.currentThread().getName());
        }
    }
}

